package org.mogu.service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.mogu.Welcome;
import org.mogu.db.ActiveUserHelper;
import org.mogu.staticvalue.Convert;
import org.mogu.tools.UrlSync;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.ProgressDialog;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.DatabaseUtils.InsertHelper;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;

public class InfoSync {
	public InfoSync() {
		Log.e("init", "new InfoSync");
	}

	DefaultHttpClient client;
	HttpResponse httpResponse;
	HttpPost getResult = null;
	HttpGet getMethod = null;

	String updateTime;
	String lastUpdate;
	String noticetitle;
	String noticecontent;
	String noticecode;

	String[] planurl;

	Date currentNow;
	int num = 0;

	boolean down = true;

	ProgressDialog dialog;

	List<NameValuePair> nameValuePair;

	SQLiteDatabase readdb = null;
	SQLiteDatabase wdb = null;
	Welcome welcome = null;
	public ActiveUserHelper auh = null;
	boolean cdstatus = false;
	String imgreg = "\\[\\*[A-Za-z]*/[-0-9A-Z]*/[_A-Za-z0-9]*\\*\\]";// 图片过滤正则
	Pattern pattern = Pattern.compile(imgreg);
	Matcher matcher = null;

	// ArrayList<HttpGet> httpList=new ArrayList<HttpGet>();

	// private Handler handler = new Handler();
	Map<String, ArrayList<String>> appMap;
	Map<String, String> userAappMap = new HashMap<String, String>();

	public void sync(ActiveUserHelper au) {
		// infoallUrl = urls;
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			cdstatus = true;
		}
		auh = au;
		try {
			synchronized (InfoSync.class) {
				if (lastUpdate == null) {
					readdb = auh.getReadableDatabase();
					Cursor activelist = readdb
							.rawQuery(
									"select username,password,writepwd,updateTime,lastUpdate,appparam from activeuser order by isactive desc",
									null);

					if (activelist.getCount() == 0) {
						activelist.close();
						return;
					}
					activelist.moveToFirst();
					if ("1".equals(activelist.getString(2))) {
						updateTime = activelist.getString(3);
						lastUpdate = activelist.getString(4);
					} else {
						activelist.close();
						return;
					}
					activelist.close();
				}
			}

			String url;

			currentNow = new Date();
			if (lastUpdate == null
					|| "".equals(lastUpdate)
					|| !lastUpdate.contains(":")
					|| (currentNow.getTime() - Convert.format1
							.parse(lastUpdate).getTime()) / (3600 * 24 * 1000) >= 1) {
				url = Convert.hosturl + "/InfoAll";
				UrlSync urlSync = new UrlSync();
				urlSync.setNotice(false);
				urlSync.setUri(url);
				urlSync.setMaincode("main");
				urlSync.setSyncType(UrlSync.INFOALL);
				Convert.syncList.add(urlSync);

			}

		} catch (Exception t) {
			Log.e("E", t.getMessage() == null ? "" : t.getMessage());
			Log.e("DB", "InfoSync-220");

		}
	}

	// private void getAppParam(String username, String code) {
	// try {
	// synchronized (InfoSync.class) {
	// readdb = auh.getReadableDatabase();
	// String[] userappAr = { Convert.uname, code };
	// Cursor userapp = readdb
	// .rawQuery(
	// "select appparm from userapp where username=? and code=?",
	// userappAr);
	//
	// userapp.moveToFirst();
	// while (!userapp.isAfterLast()) {
	// String s = userapp.getString(0);
	// userAappMap.put(Convert.uname + code, s);
	// userapp.moveToNext();
	// }
	// userapp.close();
	// // readdb.close();
	// }
	// } catch (Exception t) {
	// Log.e("E", t.getMessage() == null ? "" : t.getMessage());
	// Log.e("getAppParam-u", Convert.uname);
	// Log.e("getAppParam-c", code);
	// Log.e("DB", "InfoSync-getAppParam");
	// }
	//
	// }
	// private void request(String uri) {
	// Log.e("url", uri);
	// UrlSync urlSync=new UrlSync();
	// urlSync.setUri(uri);
	// Convert.syncList.add(urlSync);
	// return;
	// }

	public void savecontnet(String strResult, ActiveUserHelper auh,
			UrlSync urlSync) {
		this.auh = auh;
		boolean hasURI = false;
		boolean hasURI2 = false;
		synchronized (InfoSync.class) {
			try {
				long t1 = System.currentTimeMillis();
				if (wdb == null || !wdb.isOpen()) {
					wdb = auh.getReadableDatabase();
				}
				// 返回的xml
				String[] selectionArgs = { Convert.uname };

				DocumentBuilderFactory factory = DocumentBuilderFactory
						.newInstance();
				DocumentBuilder db = factory.newDocumentBuilder();
				Document document = db.parse(new java.io.ByteArrayInputStream(
						strResult.getBytes()));

				Element rootElement = document.getDocumentElement();
				long t2 = System.currentTimeMillis();
				String syncCode = null;
				String syncType = null;
				String syncTimespan = null;

				ContentValues activeuser = new ContentValues();
				syncCode = rootElement.getAttribute("code");
				String[] userappArg = { Convert.uname, syncCode };
				if ("main".equals(syncCode)) {
					ContentValues auser = new ContentValues();
					// activeuser.put("code",
					// data.getAttribute("code"));
					currentNow = new Date();
					auser.put("lastUpdate", Convert.format1.format(currentNow));
					String[] w = { Convert.uname };
					wdb.update("activeuser", auser, "username=?", w);
				} else {
					if (rootElement.hasAttribute("type")) {
						syncType = rootElement.getAttribute("type");
						syncTimespan = rootElement.getAttribute("timespan");
						currentNow = new Date();
						if ("infoupdate".equals(syncType)) {
							activeuser.put("infoupdateTimeNum", syncTimespan);
							activeuser.put("infoupdateUpdateTime",
									Convert.format1.format(currentNow));

							Convert.userAppTimeSpanMap.put(syncCode,
									Long.valueOf(syncTimespan));
						}
						if ("infoall".equals(syncType)) {
							activeuser.put("infoallTimeNum", syncTimespan);
							activeuser.put("infoallUpdateTime",
									Convert.format1.format(currentNow));
						}

						int num = wdb.update("userapp", activeuser,
								"username=? and code=?", userappArg);
						if (num == 0) {
							activeuser.put("username", Convert.uname);
							activeuser.put("code", syncCode);
							wdb.insert("userapp", null, activeuser);
						}
					}
				}

				String code;

				readdb = auh.getReadableDatabase();
				Cursor contentlist = readdb.rawQuery(
						"select code from content where username=?",
						selectionArgs);
				StringBuffer codes = new StringBuffer();
				String c = ",";
				codes.append(c);
				contentlist.moveToFirst();
				while (!contentlist.isAfterLast()) {
					codes.append(contentlist.getString(0));
					codes.append(c);
					contentlist.moveToNext();
				}
				contentlist.close();
				String codeString = codes.toString();
				Cursor imglist = readdb.rawQuery("select code from photo ",
						null);
				StringBuffer imagelist = new StringBuffer();
				imagelist.append(c);
				imglist.moveToFirst();
				while (!imglist.isAfterLast()) {
					imagelist.append(imglist.getString(0));
					imagelist.append(c);
					imglist.moveToNext();
				}
				imglist.close();
				String imageString = imagelist.toString();
				imageString += getImgLibStr();
				wdb.beginTransaction();

				NodeList imgList = rootElement.getElementsByTagName("lib");
				if (imgList != null && imgList.getLength() > 0) {
					saveImageLib(rootElement, imgList);
				}

				NodeList nodeList = rootElement.getElementsByTagName("data");

				activeuser = new ContentValues();
				boolean isnotice = false;
				if (rootElement.hasAttribute("noticetitle")) {
					noticetitle = rootElement.getAttribute("noticetitle");
					urlSync.setNoticeTitle(noticetitle);
					isnotice = true;

				}
				if (rootElement.hasAttribute("noticecode")) {
					noticecode = rootElement.getAttribute("noticecode");
					urlSync.setNoticeCode(noticecode);
					isnotice = true;

				}
				if (rootElement.hasAttribute("noticecontent")) {
					noticecontent = rootElement.getAttribute("noticecontent");
					urlSync.setNoticeContent(noticecontent);
					isnotice = true;

				}
				urlSync.setNotice(isnotice);
				if (rootElement.hasAttribute("appdata")) {
					String t = rootElement.getAttribute("appdata");
					Convert.appparam = t.replace("amp;", "");// 更新应用参数
					activeuser.put("appparam", t.replace("amp;", ""));

				}

				if (activeuser.size() > 0) {
					wdb.update("activeuser", activeuser, "username=?",
							selectionArgs);
				}
				if (rootElement.hasAttribute("appcode")) {
					ContentValues userapp = new ContentValues();
					String tt = null;
					if (rootElement.hasAttribute("appparm")) {
						tt = rootElement.getAttribute("appparm");
						userapp.put("appparm", tt.replace("amp;", ""));

					}
					String t = rootElement.getAttribute("appcode");
					if (tt != null) {
						Convert.userAappMap.put(t, tt.replace("amp;", ""));
					}
					if (userapp.size() > 0) {
						String[] wh = { Convert.uname, t };
						Cursor appcursor = readdb
								.rawQuery(
										"select code from userapp where username=? and code=?",
										wh);
						int p = appcursor.getCount();
						appcursor.close();
						if (p == 0) {
							userapp.put("code", t);
							userapp.put("username", Convert.uname);
							wdb.insert("userapp", null, userapp);

						} else {
							wdb.update("userapp", userapp,
									"username=? and code=?", wh);
						}

					}

				}
				if (rootElement.hasAttribute("verson")
						|| rootElement.hasAttribute("download")) {
					ContentValues appverson = new ContentValues();
					String verson = rootElement.getAttribute("verson");
					String download = rootElement.getAttribute("download");
					appverson.put("newverson", verson);
					appverson.put("uri", download);
					wdb.update("appverson", appverson, "id=1", null);
				}

				InsertHelper ih = new InsertHelper(wdb, "content");
				final int codenum = ih.getColumnIndex("code");
				final int fathernum = ih.getColumnIndex("father");
				final int titlenum = ih.getColumnIndex("title");
				final int updateSpanTimenum = ih
						.getColumnIndex("updateSpanTime");
				final int replyTypenum = ih.getColumnIndex("replyType");
				final int maincodenum = ih.getColumnIndex("maincode");
				final int levelnum = ih.getColumnIndex("level");
				final int statusnum = ih.getColumnIndex("status");
				final int lastUpdateTimenum = ih
						.getColumnIndex("lastUpdateTime");
				final int contentnum = ih.getColumnIndex("content");
				final int usernamenum = ih.getColumnIndex("username");

				InsertHelper ihimg = new InsertHelper(wdb, "photo");
				final int imgcode = ihimg.getColumnIndex("code");
				final int imglib = ihimg.getColumnIndex("lib");
				final int imgtype = ihimg.getColumnIndex("type");
				final int imgusername = ihimg.getColumnIndex("username");
				final int imgisDown = ihimg.getColumnIndex("isDown");
				final int imgappid = ihimg.getColumnIndex("appid");

				String content;
				String imgcodestr;
				String imglibstr;
				String imgstr;
				String imgappidstr;
				int imgnum;
				int imgnum2;
				int isDown = 0;
				String imgtypedefault = ".jpg";

				for (int i = 0; i < nodeList.getLength(); i++) {
					if (hasURI != hasURI2) {
						hasURI = false;
						hasURI2 = false;
					}

					Element data = (Element) nodeList.item(i);
					code = data.getAttribute("code");
					String[] whereArgs = { code, Convert.uname };
					if ("101".equals(data.getAttribute("level"))) {
						hasURI2 = true;
					}
					if (data.getAttribute("status").equals("0")) {
						wdb.delete("content", "code=? and username=?",
								whereArgs);
						// String[] whereArgs2 = { code+"-", Convert.uname };
						wdb.execSQL("delete from content where code like '"
								+ code + "-%' and username='" + Convert.uname
								+ "'");
						// newcount++;
						// wdb.delete("content",
						// "code like '?%' and username=?",
						// whereArgs2);
					} else {

						if (codeString.indexOf("," + code + ",") == -1) {//  新增content
							ih.prepareForInsert();
							ih.bind(codenum, data.getAttribute("code"));
							ih.bind(fathernum, data.getAttribute("father"));
							if (data.hasAttribute("title")) {
								ih.bind(titlenum, data.getAttribute("title"));
							}
							if (data.hasAttribute("updateSpanTime")) {
								ih.bind(updateSpanTimenum,
										data.getAttribute("updateSpanTime"));
							}
							if (data.hasAttribute("replyType")) {
								ih.bind(replyTypenum,
										data.getAttribute("replyType"));
								if ("16".equals(data.getAttribute("replyType"))) {
									hasURI = true;
								}
							}
							ih.bind(maincodenum, data.getAttribute("maincode"));
							ih.bind(levelnum, data.getAttribute("level"));

							ih.bind(statusnum, data.getAttribute("status"));
							ih.bind(lastUpdateTimenum,
									data.getAttribute("lastUpdateTime"));
							if (data.getChildNodes().getLength() >= 1) {

							}
							content = "";
							for (int m = 0; m < data.getChildNodes()
									.getLength(); m++) {
								content += data.getChildNodes().item(m)
										.getNodeValue();
							}
							ih.bind(contentnum,
									content.replaceAll("\\[\\(\\)\\]", "\n"));
							ih.bind(usernamenum, Convert.uname);
							ih.execute();
							codeString += data.getAttribute("code") + c;
							if (content != null && !"".equals(content)) {
								matcher = pattern.matcher(content);
								while (matcher.find()) {
									imgstr = matcher.group();
									imgnum = imgstr.indexOf("/");
									imgnum2 = imgstr.indexOf("/", imgnum + 1);
									imglibstr = imgstr.substring(2, imgnum);
									imgcodestr = imgstr.substring(imgnum + 1,
											imgnum2);
									imgappidstr = imgstr.substring(imgnum2 + 1,
											imgstr.length() - 2);
									if (imageString.indexOf("," + imgcodestr
											+ ",") == -1) {
										ihimg.prepareForInsert();
										ihimg.bind(imgcode, imgcodestr);
										ihimg.bind(imglib, imglibstr);
										ihimg.bind(imgtype, imgtypedefault);
										ihimg.bind(imgusername, Convert.uname);
										ihimg.bind(imgisDown, isDown);
										ihimg.bind(imgappid, imgappidstr);
										ihimg.execute();
										imageString += imgcodestr + c;
									}
								}
							}
							// newcount++;

						} else {// 修改content
							activeuser = new ContentValues();
							activeuser.put("father",
									data.getAttribute("father"));
							if (data.hasAttribute("title")) {
								activeuser.put("title",
										data.getAttribute("title"));
							}
							if (data.hasAttribute("updateSpanTime")) {
								activeuser.put("updateSpanTime",
										data.getAttribute("updateSpanTime"));
							}
							if (data.hasAttribute("replyType")) {
								activeuser.put("replyType",
										data.getAttribute("replyType"));
								if ("16".equals(data.getAttribute("replyType"))) {
									hasURI = true;
								}
							}

							activeuser.put("maincode",
									data.getAttribute("maincode"));
							activeuser.put("level", data.getAttribute("level"));
							activeuser.put("status",
									data.getAttribute("status"));
							activeuser.put("lastUpdateTime",
									data.getAttribute("lastUpdateTime"));
							content = "";
							for (int m = 0; m < data.getChildNodes()
									.getLength(); m++) {
								content += data.getChildNodes().item(m)
										.getNodeValue();
							}
							if (content != null) {
								activeuser.put("content", content.replaceAll(
										"\\[\\(\\)\\]", "\n"));
							}
							if (content != null && !"".equals(content)) {
								matcher = pattern.matcher(content);
								while (matcher.find()) {
									imgstr = matcher.group();
									imgnum = imgstr.indexOf("/");
									imgnum2 = imgstr.indexOf("/", imgnum + 1);
									imglibstr = imgstr.substring(2, imgnum);
									imgcodestr = imgstr.substring(imgnum + 1,
											imgnum2);
									imgappidstr = imgstr.substring(imgnum2 + 1,
											imgstr.length() - 2);
									if (imageString.indexOf("," + imgcodestr
											+ ",") == -1) {
										ihimg.prepareForInsert();
										ihimg.bind(imgcode, imgcodestr);
										ihimg.bind(imglib, imglibstr);
										ihimg.bind(imgtype, imgtypedefault);
										ihimg.bind(imgusername, Convert.uname);
										ihimg.bind(imgisDown, isDown);
										ihimg.bind(imgappid, imgappidstr);
										ihimg.execute();
										imageString += imgcodestr + c;
									}
								}
							}

							wdb.update("content", activeuser,
									"code=? and username=?", whereArgs);
							// newcount++;
						}

					}

				}

				wdb.setTransactionSuccessful();

				long t3 = System.currentTimeMillis();
				Log.i("One time", String.valueOf(t2 - t1));
				Log.i("Two time", String.valueOf(t3 - t2));
				// if (this.context != null) {
				// this.context.imgsync();
				// }
			} catch (Exception t) {
				Log.e("E", t.getMessage() == null ? "" : t.getMessage());
				Log.e("DB", "InfoSync-438");

			} finally {
				// wdb.setLockingEnabled(true );
				wdb.endTransaction();
			}
		}
		if (hasURI == hasURI2 && hasURI == true) {
			updateAppURI();
		}
		// return newcount;
	}

	private String getImgLibStr() {
		String c = ",";
		String cr = ":";
		Cursor imglist = readdb
				.rawQuery("select code,var from photoLib ", null);
		StringBuffer imagelist = new StringBuffer();
		imagelist.append(c);
		imglist.moveToFirst();
		while (!imglist.isAfterLast()) {
			imagelist.append(imglist.getString(0));
			imagelist.append(cr);
			imagelist.append(imglist.getString(1));
			imagelist.append(c);
			imglist.moveToNext();
		}
		imglist.close();
		String imageString = imagelist.toString();
		return imageString;
	}

	private void saveImageLib(Element rootElement, NodeList nodeList) {
		InsertHelper ihimg = new InsertHelper(wdb, "photoLib");
		final int imgcode = ihimg.getColumnIndex("code");
		final int imglib = ihimg.getColumnIndex("lib");
		final int imggroup = ihimg.getColumnIndex("groupid");
		final int imgtype = ihimg.getColumnIndex("type");
		final int imgusername = ihimg.getColumnIndex("username");
		final int imgisDown = ihimg.getColumnIndex("isDown");
		final int imgappid = ihimg.getColumnIndex("appid");
		final int imgvar = ihimg.getColumnIndex("var");

		String imgcodestr = "";
		String imglibstr;
		String imggroupstr;
		String imgappidstr = rootElement.getAttribute("codeid");
		;
		String imgvarstr;
		String imggrouptext;
		int isDown = 0;
		String imgtypedefault = ".jpg";

		String[] whereArgs = new String[2];
		whereArgs[1] = Convert.uname;
		ContentValues photolib;
		String imageString = getImgLibStr();
		String c = ",";
		String cr = ":";
		ContentValues imgContent;
		String[] grouparr = new String[2];
		grouparr[0] = Convert.uname;
		int num = 0;

		for (int i = 0; i < nodeList.getLength(); i++) {

			Element data = (Element) nodeList.item(i);
			imglibstr = data.getAttribute("name");
			NodeList groupList = data.getElementsByTagName("group");
			for (int j = 0; j < groupList.getLength(); j++) {
				Element group = (Element) groupList.item(j);
				imggroupstr = group.getAttribute("name");
				imggrouptext = group.getAttribute("text");
				imgContent = new ContentValues();
				grouparr[1] = imggroupstr;
				int l = imggrouptext.indexOf("(");
				if (l != -1) {
					imgContent.put("name", imggrouptext.substring(0, l));
				} else {
					imgContent.put("name", imggrouptext);
				}

				num = wdb.update("photoGroup", imgContent,
						"username=? and groupid=?", grouparr);
				if (num == 0) {
					imgContent.put("username", Convert.uname);
					imgContent.put("groupid", imggroupstr);
					wdb.insert("photoGroup", null, imgContent);
				}
				NodeList imgList = group.getElementsByTagName("img");
				for (int k = 0; k < imgList.getLength(); k++) {
					Element img = (Element) imgList.item(k);
					imgcodestr = img.getAttribute("id");
					imgvarstr = img.getAttribute("var");

					if (imageString.indexOf(c + imgcodestr + cr) == -1) {
						ihimg.prepareForInsert();
						ihimg.bind(imgcode, imgcodestr);
						ihimg.bind(imglib, imglibstr);
						ihimg.bind(imggroup, imggroupstr);
						ihimg.bind(imgtype, imgtypedefault);
						ihimg.bind(imgusername, Convert.uname);
						ihimg.bind(imgisDown, isDown);
						ihimg.bind(imgappid, imgappidstr);
						ihimg.bind(imgvar, imgvarstr);
						ihimg.execute();
						imageString += imgcodestr + cr + imgvarstr + c;
					} else if (imageString.indexOf(c + imgcodestr + cr
							+ imgvarstr + c) == -1) {
						photolib = new ContentValues();
						photolib.put("var", imgvarstr);
						photolib.put("isDown", 0);
						whereArgs[0] = imgcodestr;
						wdb.update("photoLib", photolib,
								"code=? and username=?", whereArgs);
					}

				}
			}
		}
	}

	private void updateAppURI() {
		try {
			synchronized (InfoSync.class) {
				readdb = auh.getReadableDatabase();
				String[] userappAr = { Convert.uname };
				ArrayList<String> uricode;
				Cursor userapp = readdb
						.rawQuery(
								"select father from content where username=? and level='102' and replyType='16' and content='1'",
								userappAr);

				userapp.moveToFirst();
				uricode = new ArrayList<String>();
				while (!userapp.isAfterLast()) {
					uricode.add(userapp.getString(0));
					userapp.moveToNext();
				}
				userapp.close();
				// readdb.close();
				for (int i = 0; i < uricode.size(); i++) {
					getContentTitleByCode(Convert.uname, uricode.get(i));
				}
			}
			GetSyncUrl getSyncUrl = new GetSyncUrl(auh);
			getSyncUrl.init();
		} catch (Exception t) {
			Log.e("E", t.getMessage() == null ? "" : t.getMessage());
			Log.e("DB", "InfoSync-updateAppURI");
		}

	}

	private void getContentTitleByCode(String username, String code) {
		try {
			readdb = auh.getReadableDatabase();
			String[] userappAr = { username, code };
			String uricode = "";
			Cursor userapp = readdb.rawQuery(
					"select title from content where username=? and code=?",
					userappAr);

			userapp.moveToFirst();

			while (!userapp.isAfterLast()) {
				uricode = userapp.getString(0);
				userapp.moveToNext();
			}
			userapp.close();
			// readdb.close();
			if (!"".equals(uricode)) {
				String[] uri = uricode.split(";")[1].split(",");
				String appcode = uricode.split(";")[0];
				String[] whereArgs = { appcode, username };
				wdb = auh.getWritableDatabase();
				wdb.delete("app", "code=? and username=?", whereArgs);
				String[] url;
				ContentValues app;
				for (int i = 0; i < uri.length; i++) {
					url = uri[i].split(":");
					if (url.length == 2) {
						app = new ContentValues();
						app.put("username", username);
						app.put("code", appcode);
						app.put("appid", url[0]);
						app.put("url", "http://" + url[1]);
						wdb.insert("app", null, app);
					}
				}
			}
		} catch (Exception t) {
			Log.e("E", t.getMessage() == null ? "" : t.getMessage());
			Log.e("DB", "InfoSync-getContentTitleByCode");
		}

	}
}
